package mx.vlabs.soapdroid.wsdl2java.artifactbuilder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import mx.vlabs.soapdroid.wsdl2java.Artifact;
import mx.vlabs.soapdroid.wsdl2java.ArtifactLoader;

public abstract class ArtifactBuilder {
	
	private ArtifactLoader loader;
	private Artifact artifact;
	private String packageName;
	
	public String getPackageName() {
		return packageName;
	}

	public static final String PACKAGE_NAME_KEY = "packageName";
	
	protected ArtifactBuilder(String packageName){
		this.loader = new ArtifactLoader(getArtifactType(),getArtifactType());
		this.artifact = loader.load();
		this.packageName = packageName;
		this.artifact.setParam(PACKAGE_NAME_KEY, packageName);
	}

	protected Artifact getArtifact(){
		return artifact;
	}
	
	protected ArtifactLoader getArtifactLoader(){
		return loader;
	}
	
	public abstract String build();
	public abstract String getArtifactType();
	
	public void toFile(String path) throws IOException{
		
		String fullPath = buildPathFromPackageName(path,packageName);
		
		String artifactCode = build();
		
		Writer writer = null;
	    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fullPath+"/"+artifact.getName()+ArtifactLoader.JAVA_EXTENSION), "utf-8"));
	    writer.write(artifactCode);
	    writer.close();

	}
	
	public String buildPathFromPackageName(String basePath,String packageName){
		
		File baseDir = new File(basePath);
		
		if(!baseDir.isDirectory())
		return null;
		
		boolean success = false;
		
		String fullPath = basePath+"/src/"+generatePathFromPackage(packageName);
		
		File path = new File(fullPath);
		
		if(!path.exists()){
			success = path.mkdirs();
		}else{
			success = true;
		}
		
		return success ? fullPath : null;
		
	}
		
	private String generatePathFromPackage(String packageName){
		
		return packageName.replace(".", "/");
		
	}

}
